﻿using Appliaction.Dto.DB;
using Domain.Entitys.DB;
using Domain.Entitys.Inv;
using Domain.IRepositorys.DB;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace EFCore.Repositorys.DB
{
    public class Db_warehouseRepositorys: DB_warehouse
    {
        private readonly MyDbContext myDbContext;

        public Db_warehouseRepositorys(MyDbContext myDbContext )
        {
            this.myDbContext = myDbContext;
        }
        /// <summary>
        /// 查询总条数(可以根据仓库编码和仓库名称)
        /// </summary>
        /// <param name="warehouse_code"></param>
        /// <param name="warehouse_name"></param>
        /// <returns></returns>del_flag
        /// <exception cref="NotImplementedException"></exception>
        public int Select_count_warehouse(string warehouse_code, string warehouse_name)
        {
            
            IQueryable<Warehouse> query = myDbContext.db_warehouse.Where(e => e.Del_flag == '0');
            //条件判断
            if (!string.IsNullOrEmpty(warehouse_code)) {
                query = query.Where(e => e.Warehouse_code.Contains( warehouse_code));
            }
            if (!string.IsNullOrEmpty(warehouse_name))
            {
                query = query.Where(e => e.Warehouse_name.Contains(warehouse_name));
            }
            //返回总条数
            return query.Count();
        }
        /// <summary>
        /// 分页查询 
        /// </summary>
        /// <param name="warehouse_code"></param>
        /// <param name="warehouse_name"></param>
        /// <param name="currentPage"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public List<Warehouse> Select_fy_warehouse(string warehouse_code, string warehouse_name, int currentPage, int pageSize)
        {
            //创建逻辑状态为0的查询
            IQueryable<Warehouse> query = myDbContext.db_warehouse.Where(e => e.Del_flag == '0');
            //条件判断
            if (!string.IsNullOrEmpty(warehouse_code))
            {
                query = query.Where(e => e.Warehouse_code.Contains(warehouse_code));
            }
            if (!string.IsNullOrEmpty(warehouse_name))
            {
                query = query.Where(e => e.Warehouse_name.Contains(warehouse_name)); 
            }

            //添加分页
            var pages = query.Skip((currentPage-1)*pageSize).Take(pageSize).ToList();

            return pages;
        }

     

        /// <summary>
        /// 修改冻结状态
        /// </summary>
        /// <param name="id"></param>
        /// <param name="Warehouse_freeze"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>  
        public async Task<int> warehouse_Frozenstate(int id, char Warehouse_freeze)
        {
            Warehouse warehouse = await myDbContext.db_warehouse.FindAsync(id);

            if (warehouse == null) {
                return 0;
            }
            if (warehouse.Del_flag != '0')
            {

                return 0;
            }
            if (Warehouse_freeze == '0')
            {
                warehouse.Warehouse_freeze = '1';
            }
            else {
                warehouse.Warehouse_freeze = '0';
            }
            return await myDbContext.SaveChangesAsync();
        }
        /// <summary>
        /// 仓库名称唯一性判断
        /// </summary>
        /// <param name="warehouse_name"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<int> Warehouse_name_judgment(string warehouse_name)
        {
            return await myDbContext.db_warehouse
            .Where(w => w.Warehouse_name == warehouse_name && w.Del_flag == '0')
            .CountAsync();
        }
        /// <summary>
        /// 仓库编码唯一性判断
        /// </summary>
        /// <param name="warehouse_code"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<int> Warehouse_code_judgment(string warehouse_code)
        {
            return await myDbContext.db_warehouse
             .Where(w => w.Warehouse_code == warehouse_code && w.Del_flag == '0')
              .CountAsync();
        }


        /// <summary>
        /// 逻辑删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<int> warehouse_tombstone(string warehouse_code)
        {
      
          var inv_stock=await myDbContext.inv_stock.Where(e=>e.Warehouse_Code==warehouse_code && e.Del_Flag== '0').FirstOrDefaultAsync();
            if (inv_stock != null && inv_stock.stock_numder > 0)
            {
                // 库存存在且数量 > 0，不能删除
                return 0;
            }
            //库存表有数据
            var warehouse_zone=await myDbContext.db_warehouse_zone.Where(e=>e.warehouse_code == warehouse_code && e.Del_flag == '0').FirstOrDefaultAsync();

            if (warehouse_zone != null)
            {
                return 0;
            }

            var warehouse = await myDbContext.db_warehouse.Where(e=>e.Warehouse_code == warehouse_code && e.Del_flag=='0').FirstOrDefaultAsync();
                if (warehouse == null)
                    {
                           throw new Exception("仓库不存在");
                     }
                    warehouse.Del_flag = '1';


                return await myDbContext.SaveChangesAsync();
            
        }
        /// <summary>
        /// 添加仓库
        /// </summary>
        /// <param name="warehouse"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<int> Warehouse_add(Warehouse warehouse)
        {
            await myDbContext.db_warehouse.AddAsync(warehouse);
            return await myDbContext.SaveChangesAsync();
        }
        /// <summary>
        /// 修改仓库信息
        /// </summary>
        /// <param name="warehouse"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<int> Warehouse_update(Warehouse warehouse)
        {
            //主键
            //Warehouse warehouse_update = await myDbContext.db_warehouse.FindAsync(warehouse.Warehouse_code);


            var warehouse_update = await myDbContext.db_warehouse
        .FirstOrDefaultAsync(w => w.Warehouse_code == warehouse.Warehouse_code);
            if (warehouse_update == null)
            {
                return 0;
            }
            warehouse_update.Warehouse_code = warehouse.Warehouse_code;
            warehouse_update.Warehouse_name = warehouse.Warehouse_name;
            warehouse_update.Warehouse_manager = warehouse.Warehouse_manager;
            warehouse_update.Warehouse_capacity=warehouse.Warehouse_capacity;
            warehouse_update.Warehouse_address = warehouse.Warehouse_address;
            warehouse_update.Warehouse_freeze = warehouse.Warehouse_freeze;
            warehouse_update.remarks=warehouse.remarks;
            warehouse_update.Update_by = warehouse.Update_by;
            warehouse_update.Update_time = warehouse.Update_time;
            warehouse_update.Del_flag = warehouse.Del_flag;
            myDbContext.db_warehouse.Update(warehouse_update);
            return await myDbContext.SaveChangesAsync();
        }

        /// <summary>
        /// 分页条件查询产品库存信息
        /// </summary>
        /// <param name="productName">产品名称/编号</param>
        /// <param name="dict_code">计量单位</param>
        /// <param name="currentPage">当前页</param>
        /// <param name="pageSize">每页显示数</param>
        /// <returns></returns>
        public async Task<List<inv_stock>> GetInv_StockAsync(string productName, int dict_code, int currentPage, int pageSize)
        {
            var query = myDbContext.inv_stock.Where(s => s.Del_Flag =='0');
            if (!string.IsNullOrEmpty(productName))
            {
                query = query.Where(s => s.stock_name.Contains(productName) || s.pro_code.Contains(productName));
            }
            if (dict_code > 0)
            {
                query = query.Where(s => s.dict_code == dict_code);
            }
            if (currentPage > 0 && pageSize > 0)
            {
                query = query.Skip((currentPage - 1) * pageSize).Take(pageSize);
            }
            return await query.ToListAsync();
        }

        /// <summary>
        /// 条件查询产品库存信息总数
        /// </summary>
        /// <param name="productName"></param>
        /// <param name="dict_code"></param>
        /// <returns></returns>
        public async Task<int> Inv_StockCountAsync(string productName, int dict_code)
        {
            var query = myDbContext.inv_stock.Where(s => s.Del_Flag == '0');
            if (!string.IsNullOrEmpty(productName))
            {
                query = query.Where(s => s.stock_name.Contains(productName) || s.pro_code.Contains(productName));
            }
            if (dict_code > 0)
            {
                query = query.Where(s => s.dict_code == dict_code);
            }
            return await query.CountAsync();
        }

        /// <summary>
        /// 根据产品编号查询产品库存信息
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        public Task<inv_stock> GetInv_StockByCodeAsync(string code)
        {
            return myDbContext.inv_stock.FirstOrDefaultAsync(s => s.pro_code == code && s.Del_Flag == '0');
        }
        /// <summary>
        /// 根据产品编号查询产品库存信息
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        public Task<inv_stock> GetInv_StockByCodeLocationCodeAsync(string code, string LocationCode)
        {
            return myDbContext.inv_stock.FirstOrDefaultAsync(s => s.pro_code == code &&s.Location_Code == LocationCode && s.Del_Flag == '0');
        }
        /// <summary>
        /// 查询所有仓库信息
        /// </summary>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public List<Warehouse> WarehouseBy_Select_Async()
        {
            var weahouse = myDbContext.db_warehouse.Where(e => e.Del_flag == '0'  && e.Warehouse_freeze == '0').ToList();
           return weahouse;
        }
        /// <summary>
        /// 修改仓库关联,库区,库位信息
        /// </summary>
        /// <param name="warehouse_code"></param>
        /// <param name="zone_code"></param>
        /// <param name="location_code"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<int> Warehouse_update_liaison(List<Db_Weahouse_capacityUpdateDto> updateRequests)
        {
            using var transaction = await myDbContext.Database.BeginTransactionAsync();

            try
            {
                // 分组处理相同库位的更新请求
                var groupedRequests = updateRequests
                    .GroupBy(r => new { r.warehouse_code, r.zone_code, r.location_code })
                    .Select(g => new {
                        g.Key.warehouse_code,
                        g.Key.zone_code,
                        g.Key.location_code,
                        TotalQuantity = g.Sum(x => x.Othwrproddtl_numder)
                    });

                foreach (var request in groupedRequests)
                {
                    // 查询并更新库区信息
                    var warehouseZone = await myDbContext.db_warehouse_zone
                        .Where(w => w.zone_code == request.zone_code
                                    && w.Del_flag == '0'
                                    && w.warehouse_code == request.warehouse_code
                                    && w.zone_freeze == '0')
                        .FirstOrDefaultAsync();

                    if (warehouseZone == null)
                    {
                        await transaction.RollbackAsync();
                        return 0; // 库区不存在或已被冻结/删除
                    }

                    warehouseZone.zone_available -= request.TotalQuantity;

                    // 查询并更新库位信息
                    var warehouseLocation = await myDbContext.db_warehouse_location
                        .Where(w => w.location_code == request.location_code
                                    && w.Del_flag == '0'
                                    && w.zone_code == request.zone_code
                                    && w.location_freeze == '0')
                        .FirstOrDefaultAsync();

                    if (warehouseLocation == null)
                    {
                        await transaction.RollbackAsync();
                        return 0; // 库位不存在或已被冻结/删除
                    }

                    warehouseLocation.location_available_capacity -= request.TotalQuantity;
                    warehouseLocation.location_used_capacity =
                        warehouseLocation.location_max_capacity -
                        warehouseLocation.location_available_capacity;
                }

                // 保存所有更改
                await myDbContext.SaveChangesAsync();
                await transaction.CommitAsync();

                return 1; // 成功
            }
            catch (Exception ex)
            {
                await transaction.RollbackAsync();
                Console.WriteLine($"Error in Warehouse_update_liaison: {ex.Message}");
                return -1; // 失败
            }
        }
        /// <summary>
        /// 查询所有仓库信息--盘点
        /// </summary>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public List<Warehouse> WarehouseBy_Selectpd()
        {
            var weahouse = myDbContext.db_warehouse.Where(e => e.Del_flag == '0').ToList();
            return weahouse;
        }

        /// <summary>
        /// 修改的时候,仓库名称唯一性判断
        /// </summary>
        /// <param name="warehouse_name"></param>
        /// <param name="warehouse_code"></param>
        /// <returns></returns>
        public async Task<int> Warehouse_name_UpdateJudgment(string warehouse_name, string warehouse_code)
        {

            return await myDbContext.db_warehouse
         .Where(w => w.Warehouse_name == warehouse_name && w.Del_flag == '0' && w.Warehouse_code != warehouse_code)
         .CountAsync();

        }

        /// <summary>
        /// 结构编码查询仓库信息
        /// </summary>
        /// <param name="warehouse_code"></param>
        /// <returns></returns>
        public List<Warehouse> WarehouseBy_Select_Async_code(string warehouse_code)
        {

            var weahouse = myDbContext.db_warehouse.Where(e => e.Del_flag == '0' && e.Warehouse_code == warehouse_code).ToList();
            return weahouse;
        }

        /// <summary>
        /// 修改仓库关联,库区,库位信息--增加容量
        /// </summary>
        /// <param name="warehouse_code"></param>
        /// <param name="zone_code"></param>
        /// <param name="location_code"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<int> Warehouse_update_liaison_newly(List<Db_Weahouse_capacityUpdateDto> db_Weahouse_CapacityUpdateDtos)
        {
            using var transaction = await myDbContext.Database.BeginTransactionAsync();

            try
            {
                // 分组处理相同库位的更新请求
                var groupedRequests = db_Weahouse_CapacityUpdateDtos
                    .GroupBy(r => new { r.warehouse_code, r.zone_code, r.location_code })
                    .Select(g => new {
                        g.Key.warehouse_code,
                        g.Key.zone_code,
                        g.Key.location_code,
                        TotalQuantity = g.Sum(x => x.Othwrproddtl_numder)
                    });

                foreach (var request in groupedRequests)
                {
                    // 查询并更新库区信息 - 增加可用容量
                    var warehouseZone = await myDbContext.db_warehouse_zone
                        .Where(w => w.zone_code == request.zone_code
                                    && w.Del_flag == '0'
                                    && w.warehouse_code == request.warehouse_code
                                    && w.zone_freeze == '0')
                        .FirstOrDefaultAsync();

                    if (warehouseZone == null)
                    {
                        await transaction.RollbackAsync();
                        return 0; // 库区不存在或已被冻结/删除
                    }

                    // 增加可用容量（原为减少）
                    warehouseZone.zone_available += request.TotalQuantity;

                    // 查询并更新库位信息 - 增加可用容量
                    var warehouseLocation = await myDbContext.db_warehouse_location
                        .Where(w => w.location_code == request.location_code
                                    && w.Del_flag == '0'
                                    && w.zone_code == request.zone_code
                                    && w.location_freeze == '0')
                        .FirstOrDefaultAsync();

                    if (warehouseLocation == null)
                    {
                        await transaction.RollbackAsync();
                        return 0; // 库位不存在或已被冻结/删除
                    }

                    // 增加可用容量（原为减少）
                    warehouseLocation.location_available_capacity += request.TotalQuantity;

                    // 重新计算已用容量（最大容量 - 可用容量）
                    warehouseLocation.location_used_capacity =
                        warehouseLocation.location_max_capacity -
                        warehouseLocation.location_available_capacity;
                }

                // 保存所有更改
                await myDbContext.SaveChangesAsync();
                await transaction.CommitAsync();

                return 1; // 成功
            }
            catch (Exception ex)
            {
                await transaction.RollbackAsync();
                Console.WriteLine($"Error in Warehouse_update_liaison: {ex.Message}");
                return -1; // 失败
            }
        }
    }
}
